<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Home extends MY_Controller {
    /**
     * @var ConsumerFindModel
     */
    public $mFind;
    /**
     * @var ConsumerFindCategoryModel
     */
    public $mFindCategory;
    /**
     * @var ConsumerFindAttributeModel
     */
    public $mAttribute;

	public function __construct(){
		parent::__construct();
        $this->loadModel('ConsumerFindModel', 'mFind', 'consumer');
        $this->loadModel('ConsumerFindCategoryModel', 'mFindCategory', 'consumer');
        $this->loadModel('ConsumerFindAttributeModel', 'mAttribute', 'consumer');
	}
	
	/**
	 * 首页
	 */
	public function index(){
		$category = $this->mFindCategory->adminPcGetList();
        $data = array(
            'category' => $category,
            'title' => '发现信息'
        );
		$this->view('find/home/index', $data, 'datatable,validation,datepicker');
	}

    /**
     * 获取数据
     */
    public function getList(){
        $data = $this->mFind->adminPcGetList();
        foreach ($data['data'] as $k => $v){
            $data['aaData'][$k][] = $v['nickname'];
            $data['aaData'][$k][] = $v['mobile'];
            $data['aaData'][$k][] = $v['title'];
            $data['aaData'][$k][] = $v['name'];
            $data['aaData'][$k][] = $v['region'];
            $data['aaData'][$k][] = $v['address'];
            $data['aaData'][$k][] = isset($v['read_number']) ? $v['read_number'] : 0;
            $status = $v['status'] == 1 ? 2 : 1;
            $data['aaData'][$k][] = "<a href='".getUrl('find/home/changeStatus?id='.$v['id']).
                "' class='ajax-request-btn deco' alert-message='是否确认".$this->status($status)."'>".$this->status($v['status'], true)."</a>";

            $data['aaData'][$k][] = dateFormat($v['addtime']);

            $btnConfig = adminCreateBtn(array(
                'label' => '详情',
                'attr' => array(
                    'href' => getUrl('find/home/details').'?id='.$v['id'],
                    'class' => 'btn btn-xs green-stripe default',
                ),
                'tag' => 'a',
                'permissions' => array(
                    'module' => 'find',
                    'key' => 'home-details'
                )
            ));
            $btnConfig .=' '. adminCreateBtn(array(
                'label' => '编辑',
                'attr' => array(
                    'href' => getUrl('find/home/edit').'?id='.$v['id'],
                    'class' => 'btn btn-xs blue-stripe default',
                ),
                'tag' => 'a',
                'permissions' => array(
                    'module' => 'find',
                    'key' => 'home-edit'
                )
            ));
            $btnConfig .=' '. adminCreateBtn(array(
                    'label' => '删除',
                    'attr' => array(
                        'href' => getUrl('find/home/delete?id='.$v['id']),
                        'class' => 'btn btn-xs red-stripe default ajax-request-btn',
                        'alert-message' => '是否确定刪除 “ '.$v['name'].' ” ?'
                    ),
                    'tag' => 'a',
                    'permissions' => array(
                        'module' => 'find',
                        'key' => 'home-delete'
                    )
                ));
            $data['aaData'][$k][] = $btnConfig;
        }
        unset($data['data']);
        echo json_encode($data);
    }

    /**
     * 修改
     */
    public function changeStatus(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf, array('id' => get('id')));
        $id = (int)get('id');
        $info = $this->mFind->getInfo($id, true);
        $status = $info['status'] == 1 ? 2 : 1;
        if($this->mFind->save(array('status' => $status), $id)){
            $this->ajaxReturn(1, '保存成功');
        }
        $this->ajaxReturn(0, '保存失败');
    }

    /**
     * 详情
     */
    public function details(){
        $id =(int)get('id');
        if (!$id){
            show_404();
        }
        $info = $this->mFind->getInfo($id);
        $data = array(
            'info' => $info,
            'title' => '信息详情'
        );
        $this->view('find/details', $data, 'datatable');
    }

    /**
     * 添加
     */
    public function add(){
        $this->loadModel('AdmSettingModel', 'mAdm', 'admin');
        $data = array(
            'category' => $this->mFindCategory->getList(),
            'ak' => $this->mAdm->get('map_key', 'deliveryman'),
            'province' => $this->mAdm->getLocationByPid(1),
            'title' => '添加',
            'add' => true,
        );
        $this->view('find/home/from', $data, 'validation,select2,webuploader,datepicker,region');
    }

    /**
     * 编辑
     */
    public function edit(){

        $id = (int)get('id');
        if (!$id){
            show_404();
        }
        $info = $this->mFind->getInfo($id);
        if (!$info){
            show_404();
        }
        $this->loadModel('AdmSettingModel', 'mSetting', 'admin');
        $attribute = $this->mAttribute->getAttributeValueList($id);
//        p($attribute);
        $data = array(
            'category' => $this->mFindCategory->getList(),
            'province' => $this->mSetting->getLocationByPid(1),
            'info' => $info,
            'attribute' => $attribute,
            'city' => $this->mSetting->getLocationByPid($info['province']),
            'county' => $this->mSetting->getLocationByPid($info['city']),
            'title' => '编辑',
            'add' => false,
        );

        $this->view('find/home/from', $data, 'validation,select2,webuploader,datepicker,region');
    }

    /**
     * 保存
     */
    public function save(){
        //表单验证
        $vConf = array(
            array('title', '标题', 'required'),
            array('content', '内容', 'required'),
            array('category_id', '分类id', 'required|is_natural_no_zero'),
            array('province', '省id', 'required|is_natural_no_zero'),
            array('city', '市id', 'required|is_natural_no_zero'),
            array('county', '区id', 'required|is_natural_no_zero'),
            array('address', '地址', 'required'),
            array('latitude', '经度', 'required'),
            array('longitude', '纬度', 'required'),
            array('status', '状态', 'required|in_list[1,2]'),
        );
        $this->formDataValidation($vConf);
        $categoryId = (int)post('category_id');
        $id = (int)post('id');
        $images = post('pic');
        if($images && count($images) > 4){
            $this->ajaxReturn(0, '图片最多上传4张');
        }
        $attrValue = post('attr_value');
        if ( ! $this->mFindCategory->getInfo($categoryId)){
            $this->ajaxReturn(0,'分类不存在');
        }
        // 查看分类下是否有特殊属性
        $attribute = $this->mAttribute->getList($categoryId);
        if (!empty($attribute) && empty($attrValue)){
            $this->ajaxReturn(0,'请填写分类下的特殊属性');
        }
        $data = array(
            'consumer_id'=>0,
            'category_id'=>$categoryId,
            'title'=>trim(post('title')),
            'content'=>trim(post('content')),
            'pic'=>json_encode(array()),
            'province'=>post('province'),
            'city'=>post('city'),
            'county'=>post('county'),
            'address'=>trim(post('address')),
            'latitude'=>trim(post('latitude')),
            'longitude'=>trim(post('longitude')),
            'read_number'=>0,
            'status'=>(int)post('status'),
            'addtime'=>time(),
        );

        $this->db->trans_begin();//开启事务
        if ($id) {
            $tA = $this->mFind->getInfo($id);
            if (!$tA){
                $this->ajaxReturn(0,'数据不存在');
            }
            $rS = $this->mFind->save($data, $id);
            if (!$rS) {
                $this->db->trans_rollback();
                $this->ajaxReturn(0, '发布失败');
            }
            $tId = $id;
        }else{
            $tId = $this->mFind->save($data);
            if (!$tId) {
                $this->db->trans_rollback();
                $this->ajaxReturn(0, '发布失败');
            }
        }
        /**
         *  移动新文件
         */

        if ($images){
            $imgPath = array();
            $path = 'uploads/find/'.$tId;
            foreach ($images as $k=>$v){
                if (stripos($v,'temp') !== FALSE){
                    $size = getimagesize($v);
                    $imgPath[] = saveTempImg($v, $path, true, $size[0], $size[1]);
                }else {
                    $imgPath[] = str_replace(base_url(), '', $v);
                }
            }
            if($id){
                $tImages = $tA['pic'];
                foreach ($tImages as $k=>$v){
                    if( ! in_array($v, $imgPath)){
                        $v = strstr($v, '?',true);
                        $tA = explode('/', $v);
                        $filename = $tA[count($tA)-1];
                        if (file_exists($v)){
                            unlink($v);
                        }
                        if (file_exists($path.'sm/'.$filename)){
                            unlink($path.'sm/'.$filename);
                        }
                        if (file_exists($path.'xs/'.$filename)){
                            unlink($path.'xs/'.$filename);
                        }
                    }
                }
            }
            $imgPath = array_slice($imgPath, 0, 3);
            if ( ! $this->mFind->save(array('pic'=>json_encode($imgPath)),$tId)){
                $this->db->trans_rollback();
                $this->ajaxReturn(0,'保存失败');
            }
        }

        if (!empty($attribute)){
            $attrData = array();
            foreach ($attrValue as $k => $v){
                $attrData[] = array(
                    'attr_id' => $k,
                    'find_id' => $tId,
                    'attr_value' => json_encode($v, JSON_UNESCAPED_UNICODE),
                );
            }
            $a = $this->mAttribute->saveBatchAttribute($attrData);
            if (!$a){
                $this->db->trans_rollback();
                $this->ajaxReturn(0,'保存失败');
            }
        }
        $this->db->trans_commit();
        $this->ajaxReturn(1,'发布成功', '', getUrl('find/home'));
    }

    /**
     * 获取特殊属性
     */
    public function getAttributeGetByCategoryId(){
        $categoryId = (int)post('category_id');
        if (!$categoryId){
            $this->ajaxReturn(0, '参数错误');
        }
        $list = $this->mAttribute->getList($categoryId);
        $this->ajaxReturn(1, '', $list);
    }

    /**
     * 获取状态显示样式
     * @param 	integer $status
     * @return	string
     */
    protected function status($status = null, $show = false){

        $config = array(1 => '隐藏', 2 => '显示');
        if( ! $status){
            return $config;
        }

        if($status && ! isset($config[$status])){
            return '';
        }

        if( ! $show){
            return $config[$status];
        }


        if($status == 1){
            return '<span class="label label-danger">'.$config[$status].'</span>';
        }else if($status == 2){
            return '<span class="label label-success">'.$config[$status].'</span>';
        }

        return'';
    }

    /**
     * 删除信息
     */
    public function delete(){
        $id = (int)get('id');
        if (!$id){
            show_404();
        }
        $info = $this->mFind->getInfo($id);
        if (!$info){
            show_404();
        }
        $this->db->trans_begin();//开启事务
        if(!($this->mFind->deleteFind($id))){
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '删除失败');
        }
        //删除浏览记录
        if(!($this->mFind->deleteApproval($id))){
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '删除失败');
        }

        $this->db->trans_commit();
        $this->ajaxReturn(1, '删除成功');
    }
}
